package com.wteam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wteam.PoJo.DTO.*;
import com.wteam.PoJo.VO.*;
import com.wteam.exception.orderException;
import com.wteam.mapper.*;
import com.wteam.service.OrderService;
import com.wteam.untils.MemberIdAndName;
import com.wteam.untils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class OrderServiceimpl implements OrderService {
    //    @Autowired
//    private OrderlogMapper orderlogMapper;
    @Autowired
    private WalletMapper walletMapper;
    @Autowired
    private Goodsmapper goodsmapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private GoodsCartmapper goodsCartmapper;
    @Autowired
    private Memberdtomapper memberdtomapper;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CouponMenmbermapper couponMenmbermapper;
    @Autowired
    private RegionMapper regionMapper;
    @Autowired
    private MemberIdAndName memberIdAndName;
    @Autowired
    private Couponmapper couponmapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private OrdernumbertwoMapper ordernumbertwoMapper;

    //这个接口还得考虑订单库存剪一下
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<orderid> buyorder(buyorder buyorder) {
        Integer memberid = memberIdAndName.Memberid(httpServletRequest.getHeader("token"));
        String membername = memberIdAndName.username(httpServletRequest.getHeader("token"));


        //1.把订单存起来
        order order = new order();
        BeanUtils.copyProperties(buyorder, order);
        order.setMemberId(memberid);

        //2.（1）查地址具体消息
        //添加地址信息
        order.setConsignee_address_path(buyorder.getProvince()
                + buyorder.getUrban());
        order.setConsigneeDetail(buyorder.getFulladdress());
//

        log.info(order.toString());

        //第二：查有没有用优惠卷，改用户优惠卷为已使用
        if (buyorder.getCouponId() != null && buyorder.getCouponId() != 0) {
            order.setUse_platform_member_coupon_id(buyorder.getCouponId());
            LambdaQueryWrapper<coupon_member> couponqw = new LambdaQueryWrapper<>();
            couponqw.eq(coupon_member::getMemberId, memberid)
                    .eq(coupon_member::getCouponId, buyorder.getCouponId())
                    .eq(coupon_member::getState, "2");
            coupon_member couponMember = couponMenmbermapper.selectOne(couponqw);
            if (couponMember == null) {

                throw new orderException("你并没有该优惠卷");
//                return Result.error("你并没有该优惠卷");
            }

            couponMember.setState("1");
            //改用户优惠卷为已使用
            redisTemplate.delete("couponlist_");
            couponMenmbermapper.updateById(couponMember);

            //有优惠卷使用改优惠卷表，已使用加一
            coupon coupon = couponmapper.selectById(buyorder.getCouponId());
            coupon.setUsedNum(coupon.getUsedNum() + 1);
            couponmapper.updateById(coupon);
        }

        //第三：有无查积分扣积分
        if (buyorder.getPoint() != null || buyorder.getPoint() != 0) {

            memberdto memberdto = memberdtomapper.selectById(memberid);
            //判断我的积分和前端发过来的积分大小的，防止前端乱传
            if (memberdto.getPoint() < buyorder.getPoint()) {
//                return Result.error("积分不足，先查一下我有多少积分，控制积分上线");
                throw new orderException("积分不足，先查一下我有多少积分，控制积分上线");
            }
            //现在是有积分，扣一下用户积分
            memberdto.setPoint(memberdto.getPoint() - buyorder.getPoint());
            memberdtomapper.updateById(memberdto);
        }
        //在订单列表说明一下使用的积分
        order.setUsepoint(buyorder.getPoint());

        //设置订单状态为1并插入数据
        order.setOrderStatus(1);


        //生成一个订单号
        long sn = IdWorker.getId();
        order.setSn(sn);
        orderMapper.insert(order);


        LambdaQueryWrapper<cart> cartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cartLambdaQueryWrapper.eq(cart::getMemberId, memberid)
                .eq(cart::getSelected, 1);
        //要存购物车，存到order_goods的表中
        List<cart> carts = goodsCartmapper.selectList(cartLambdaQueryWrapper);
        for (cart cart : carts) {
            //查商品的具体消息
            LambdaQueryWrapper<goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            goodsLambdaQueryWrapper.eq(goods::getId, cart.getGoodsId());
            goods goods = goodsmapper.selectOne(goodsLambdaQueryWrapper);
            //存到order_goods的表中
            order_goods ordergoods = new order_goods();
            ordergoods.setOrdersnId(sn);
            ordergoods.setGoodId(goods.getId());
            ordergoods.setGoodName(goods.getGoodsName());
            ordergoods.setGoodNumber(cart.getQuantity());
            ordergoods.setGoodSmall(goods.getSmall());
            ordergoods.setOneGoodPrice(goods.getPrice());
            ordergoods.setMemberId(memberid);
            ordergoods.setAfterSaleStatus(1);
            orderGoodsMapper.insert(ordergoods);
        }

        //删一下购物车
        goodsCartmapper.delete(cartLambdaQueryWrapper);

        //设置订单详情
//        orderid orderid=new orderid();
//List<order_goods>order_goods=new ArrayList<>();
//LambdaQueryWrapper<order_goods>order_goodsLambdaQueryWrapper=new LambdaQueryWrapper<>();
//order_goodsLambdaQueryWrapper.eq(com.wteam.PoJo.DTO.order_goods::getMemberId,memberid)
//        .eq(com.wteam.PoJo.DTO.order_goods::getOrdersnId,sn);
//        List<com.wteam.PoJo.DTO.order_goods> order_goods1 = orderGoodsMapper.selectList(order_goodsLambdaQueryWrapper);
        //查订单id
        LambdaQueryWrapper<order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(com.wteam.PoJo.DTO.order::getMemberId, memberid)
                .eq(com.wteam.PoJo.DTO.order::getSn, sn);
        com.wteam.PoJo.DTO.order order1 = orderMapper.selectOne(orderLambdaQueryWrapper);
        orderid orderid = new orderid();
        orderid.setOrderid(order1.getId());
        orderid.setSn(sn);
        return Result.success(orderid);


        //注意用户可能不支付


    }

    @Override
    public Result selectorder(Integer orderStatus) {
        Integer memberid = memberIdAndName.Memberid(httpServletRequest.getHeader("token"));


        List<listorder> listorders = new ArrayList<>();

        LambdaQueryWrapper<ordernumbertwo> orderLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper1.eq(ordernumbertwo::getMemberId, memberid)
                .eq(orderStatus != null && (orderStatus == 1 || orderStatus == 2 || orderStatus == 3) && orderStatus != 4
                        , ordernumbertwo::getOrderStatus, orderStatus);
        //要返回的集合
        List<ordernumbertwo> ordernumbertwos = ordernumbertwoMapper.selectList(orderLambdaQueryWrapper1);


        //查看订单
//        List<order> orders = orderMapper.selectList(orderLambdaQueryWrapper);
//        log.info(orders.toString());
        for (ordernumbertwo order : ordernumbertwos) {
            listorder listorder = new listorder();
            BeanUtils.copyProperties(order, listorder);
            listorder.setUse_platform_member_coupon_id(order.getUsePlatformMemberCouponId());
            if (order.getUsePlatformMemberCouponId() != null) {
                log.info(order.getUsePlatformMemberCouponId().toString());
            }
            //一个订单里面要传的多个商品
            List<OrderGoods> listordergoods = new ArrayList<>();

            LambdaQueryWrapper<order_goods> orderGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderGoodsLambdaQueryWrapper.eq(order_goods::getOrdersnId, order.getSn());
            //订单商品（要去一些无用的）
            List<order_goods> order_goods = orderGoodsMapper.selectList(orderGoodsLambdaQueryWrapper);

            //商品集合copy
            for (com.wteam.PoJo.DTO.order_goods order_good : order_goods) {
                OrderGoods listordergoods1 = new OrderGoods();
                BeanUtils.copyProperties(order_good, listordergoods1);
                listordergoods.add(listordergoods1);
            }
            listorder.setListordergoods(listordergoods);

            log.info(order_goods.toString());
            log.info(listordergoods.toString());
            listorders.add(listorder);
        }

        return Result.success(listorders);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result putmoney(Integer orderId, Long ordersnId) {
        Integer memberid = memberIdAndName.Memberid(httpServletRequest.getHeader("token"));

        //改订单状态为已支付
        ordernumbertwo ordernumbertwo = new ordernumbertwo();
        ordernumbertwo.setId(orderId);
        ordernumbertwo.setOrderStatus(2);
        ordernumbertwoMapper.updateById(ordernumbertwo);
        LambdaQueryWrapper<ordernumbertwo> ordernumbertwoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordernumbertwoLambdaQueryWrapper.eq(com.wteam.PoJo.DTO.ordernumbertwo::getId, orderId)
                .eq(com.wteam.PoJo.DTO.ordernumbertwo::getSn, ordersnId);


        com.wteam.PoJo.DTO.ordernumbertwo ordernumbertwo1
                = ordernumbertwoMapper.selectOne(ordernumbertwoLambdaQueryWrapper);
        log.info(ordernumbertwo1.toString());

        //改order_goods表
        LambdaQueryWrapper<order_goods> orderGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderGoodsLambdaQueryWrapper.eq(order_goods::getMemberId, memberid)
                .eq(order_goods::getOrdersnId, ordersnId);
        order_goods orderGoods = new order_goods();
        orderGoods.setAfterSaleStatus(2);
        orderGoodsMapper.update(orderGoods, orderGoodsLambdaQueryWrapper);

        //扣钱
        LambdaQueryWrapper<member_wallet> qw = new LambdaQueryWrapper<>();
        qw.eq(member_wallet::getMemberId, memberid);

        member_wallet memberWallet = walletMapper.selectOne(qw);
        if (memberWallet == null) {
            throw new orderException("还没给钱包设置密码");
        }

        if (memberWallet.getMemberWallet() < ordernumbertwo1.getDiscountFlowPrice()) {
            throw new orderException("没钱了,快去充");
        }
        //修改商品的库存
        List<order_goods> order_goods = orderGoodsMapper.selectList(orderGoodsLambdaQueryWrapper);
        for (com.wteam.PoJo.DTO.order_goods order_good : order_goods) {
            goods goods = goodsmapper.selectById(order_good.getGoodId());
            if (goods.getQuantity() < order_good.getGoodNumber()) {
                throw new orderException("现在库存不够，只有+" + order_good.getGoodNumber() + "件");
            }

            goods.setQuantity(goods.getQuantity() - order_good.getGoodNumber());
            goods.setBuyCount(goods.getBuyCount() + order_good.getGoodNumber());
            goodsmapper.updateById(goods);
        }


        memberWallet.setMemberWallet(memberWallet.getMemberWallet() - ordernumbertwo1.getDiscountFlowPrice());
        walletMapper.update(memberWallet, qw);

        String key = memberid + "_my_coupon";
        redisTemplate.delete(key);
        return Result.success("购买成功");
    }

    @Override
    public Result selectAddress(Integer id) {
        region region = regionMapper.selectById(id);
        return Result.success(region);
    }

    @Override
    public Result updateAddress(fixregion fixregion) {
        region region = new region();
        BeanUtils.copyProperties(fixregion, region);

        regionMapper.updateById(region);
        return Result.success("修改成功");
    }

    @Override
    public Result selectbuygoods(freight freight) {
        IPage<order_goods> iPage = new Page<>(freight.getPage(), freight.getPagesize());
        LambdaQueryWrapper<order_goods> qw = new LambdaQueryWrapper<>();
        Integer memberid = memberIdAndName.Memberid(httpServletRequest.getHeader("token"));
        IPage<order_goods> iPage2=new Page<>();

        if (freight.getAftersalestatus()==null){
            qw.eq(order_goods::getMemberId, memberid)
                    .ne(freight.getAftersalestatus() == null, order_goods::getAfterSaleStatus,
                           5);
            iPage2 = orderGoodsMapper.selectPage(iPage, qw);

        }
        if (freight.getAftersalestatus()!=null){
        qw.eq(order_goods::getMemberId, memberid)
                .eq(freight.getAftersalestatus() != null, order_goods::getAfterSaleStatus,
                        freight.getAftersalestatus());
         iPage2 = orderGoodsMapper.selectPage(iPage, qw);}
        log.info(iPage2.getRecords().toString());
        List<buygoods> list = new ArrayList<>();
        for (order_goods record : iPage2.getRecords()) {

            buygoods buygoods = new buygoods();
            BeanUtils.copyProperties(record, buygoods);
            list.add(buygoods);
        }
        return Result.success(list);

    }

    @Override
    public Result salestatus(Integer id) {
        order_goods order_goods = new order_goods();
        order_goods.setId(id);
        order_goods.setAfterSaleStatus(3);

        int i = orderGoodsMapper.updateById(order_goods);
        if (i != 1) {
            throw new orderException("确任失败");
        }

        return Result.success("成功收货");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> deleteorder(Integer id) {
        Integer memberid = memberIdAndName.Memberid(httpServletRequest.getHeader("token"));
        ordernumbertwo order = ordernumbertwoMapper.selectById(id);
        //查花了多少钱
        Double momey = order.getDiscountFlowPrice();
        //查用了多少积分
        Integer usepoint = order.getUsepoint();
        //积分返还
        memberdto memberdto = memberdtomapper.selectById(memberid);
        memberdto.setPoint(memberdto.getPoint() + usepoint);
        memberdtomapper.updateById(memberdto);

        Integer UsePlatformMemberCouponId = order.getUsePlatformMemberCouponId();
        //返还优惠卷
        LambdaQueryWrapper<coupon_member> coupon_memberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        coupon_memberLambdaQueryWrapper.eq(coupon_member::getMemberId, memberid)
                .eq(coupon_member::getCouponId, UsePlatformMemberCouponId);

        coupon_member couponMember = new coupon_member();
        couponMember.setState("2");
        couponMenmbermapper.update(couponMember, coupon_memberLambdaQueryWrapper);

        //查订单具体信息，改订单状态
        order.setOrderStatus(3);
        ordernumbertwoMapper.updateById(order);
        //把订单商品状态改一下
        LambdaQueryWrapper<order_goods> orderGoodsLambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        orderGoodsLambdaQueryWrapper.eq(order_goods::getOrdersnId, order.getSn());
      List<order_goods> order_goods = orderGoodsMapper.selectList(orderGoodsLambdaQueryWrapper);
        for (com.wteam.PoJo.DTO.order_goods orderGood : order_goods) {
            orderGood.setAfterSaleStatus(5);
            orderGoodsMapper.updateById(orderGood);
        }
        return Result.success("订单取消成功");
    }

    @Override
    public Result refundgoods(refundgoods refundgoods) {
        Integer memberid = memberIdAndName.Memberid(httpServletRequest.getHeader("token"));

        //查goods具体信息
        LambdaQueryWrapper<order_goods> orderGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderGoodsLambdaQueryWrapper.eq(order_goods::getId, refundgoods.getId())
                .eq(order_goods::getOrdersnId, refundgoods.getOrdersnId());
        order_goods order_goods = orderGoodsMapper.selectOne(orderGoodsLambdaQueryWrapper);
        order_goods.setAfterSaleStatus(4);
        orderGoodsMapper.updateById(order_goods);
        //计算花了多少钱
        Double money = order_goods.getOneGoodPrice() * order_goods.getGoodNumber();
        //加钱
        LambdaQueryWrapper<member_wallet> walletLambdaQueryWrapper = new LambdaQueryWrapper<>();
        walletLambdaQueryWrapper.eq(member_wallet::getMemberId, memberid);
        member_wallet memberWallet = walletMapper.selectOne(walletLambdaQueryWrapper);
        memberWallet.setMemberWallet(memberWallet.getMemberWallet() + money);
        walletMapper.updateById(memberWallet);
        return Result.success("退货成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<orderid> saveonegoods(buygood buyorder) {
        Integer memberid = memberIdAndName.Memberid(httpServletRequest.getHeader("token"));
        String membername = memberIdAndName.username(httpServletRequest.getHeader("token"));


        //1.把订单存起来
        order order = new order();

        BeanUtils.copyProperties(buyorder, order);
        order.setMemberId(memberid);
        //2.（1）查地址具体消息
        //添加地址信息
        order.setConsignee_address_path(buyorder.getProvince()
                + buyorder.getUrban());
        order.setConsigneeDetail(buyorder.getFulladdress());
//

        log.info(order.toString());

        //第二：查有没有用优惠卷，改用户优惠卷为已使用
        if (buyorder.getCouponId() != null && buyorder.getCouponId() != 0) {
            order.setUse_platform_member_coupon_id(buyorder.getCouponId());
            LambdaQueryWrapper<coupon_member> couponqw = new LambdaQueryWrapper<>();
            couponqw.eq(coupon_member::getMemberId, memberid)
                    .eq(coupon_member::getCouponId, buyorder.getCouponId())
                    .eq(coupon_member::getState, "2");
            coupon_member couponMember = couponMenmbermapper.selectOne(couponqw);
            if (couponMember == null) {

                throw new orderException("你并没有该优惠卷");
//                return Result.error("你并没有该优惠卷");
            }

            couponMember.setState("1");
            //改用户优惠卷为已使用
            redisTemplate.delete("couponlist_");
            couponMenmbermapper.updateById(couponMember);
            String key = memberid + "_my_coupon";
            redisTemplate.delete(key);
            //有优惠卷使用改优惠卷表，已使用加一
            coupon coupon = couponmapper.selectById(buyorder.getCouponId());
            coupon.setUsedNum(coupon.getUsedNum() + 1);
            couponmapper.updateById(coupon);
        }

        //第三：有无查积分扣积分
        if (buyorder.getPoint() != null || buyorder.getPoint() != 0) {
            memberdto memberdto = memberdtomapper.selectById(memberid);
            //判断我的积分和前端发过来的积分大小的，防止前端乱传
            if (memberdto.getPoint() < buyorder.getPoint()) {
//                return Result.error("积分不足，先查一下我有多少积分，控制积分上线");
                throw new orderException("积分不足，先查一下我有多少积分，控制积分上线");
            }
            //现在是有积分，扣一下用户积分
            memberdto.setPoint(memberdto.getPoint() - buyorder.getPoint());
            memberdtomapper.updateById(memberdto);
        }
        //在订单列表说明一下使用的积分
        order.setUsepoint(buyorder.getPoint());

        //设置订单状态为1并插入数据
        order.setOrderStatus(1);


        //生成一个订单号
        long sn = IdWorker.getId();
        order.setSn(sn);
        orderMapper.insert(order);

        LambdaQueryWrapper<cart> cartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cartLambdaQueryWrapper.eq(cart::getMemberId, memberid)
                .eq(cart::getSelected, 1);
        //要存购物车，存到order_goods的表中
        List<cart> carts = goodsCartmapper.selectList(cartLambdaQueryWrapper);
        //查商品的具体消息
        LambdaQueryWrapper<goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsLambdaQueryWrapper.eq(goods::getId, buyorder.getGoodId());
        goods goods = goodsmapper.selectOne(goodsLambdaQueryWrapper);
        //存到order_goods的表中
        order_goods ordergoods = new order_goods();
        ordergoods.setOrdersnId(sn);
        ordergoods.setGoodId(goods.getId());
        ordergoods.setGoodName(goods.getGoodsName());
        ordergoods.setGoodNumber(buyorder.getGoodnumber());
        ordergoods.setGoodSmall(goods.getSmall());
        ordergoods.setOneGoodPrice(goods.getPrice());
        ordergoods.setMemberId(memberid);
        ordergoods.setAfterSaleStatus(1);
        orderGoodsMapper.insert(ordergoods);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //删一下购物车


        LambdaQueryWrapper<order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(com.wteam.PoJo.DTO.order::getMemberId, memberid)
                .eq(com.wteam.PoJo.DTO.order::getSn, sn);
        com.wteam.PoJo.DTO.order order1 = orderMapper.selectOne(orderLambdaQueryWrapper);
        log.info(order1.toString());
        orderid orderid = new orderid();
        orderid.setOrderid(order1.getId());
        orderid.setSn(sn);
        return Result.success(orderid);

    }

    @Override
    public Result<listorder> orderdetial(Integer orderid) {
        listorder listorder = new listorder();
        order order = orderMapper.selectById(orderid);
        BeanUtils.copyProperties(order, listorder);

//        log.info(listorder.toString());
        Long sn = order.getSn();
        LambdaQueryWrapper<order_goods> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(order_goods::getOrdersnId, sn);
//        List<order_goods> order_goods = orderGoodsMapper.selectList(lambdaQueryWrapper);
//        log.info(order_goods.toString());
//        List<OrderGoods> list = new ArrayList<>();
//        for (com.wteam.PoJo.DTO.order_goods order_good : order_goods) {
//            OrderGoods listordergoods1 = new OrderGoods();
//            BeanUtils.copyProperties(order_goods, listordergoods1);
//            list.add(listordergoods1);
//        }
//        listorder.setListordergoods(list);


        List<order_goods> order_goods = orderGoodsMapper.selectList(lambdaQueryWrapper);
        List<OrderGoods> listordergoods = new ArrayList<>();

        //商品集合copy
        for (com.wteam.PoJo.DTO.order_goods order_good : order_goods) {
            OrderGoods listordergoods1 = new OrderGoods();
            BeanUtils.copyProperties(order_good, listordergoods1);
            listordergoods.add(listordergoods1);
        }
        listorder.setListordergoods(listordergoods);


        return Result.success(listorder);
    }
}

